(defun primep (n)
  (cond ((<= n 3) t)
	((zerop (mod n 2)) nil)
	(t (loop 
	      for i = 3 then (+ i 2)
	      until (> i (floor (sqrt n)))
	      when (zerop (mod n i)) 
	      do (return nil) 
	      finally (return t)))))

(defun drop-digit (n)
  (/ (- n (mod n 10)) 10))

(defun drop-first-digit (n)
  (mod n (expt 10 (1- (digits n)))))


(defun digits(n &optional(i 1))
  (cond ((< n 10) i)
	(t (+ 1 (digits (drop-digit n) i )))))


(defun rotate(n)
  (+ (* (expt 10 (1- (digits n))) (mod n 10)) (drop-digit n)))



(defun circular-primep-inner (n i)
  (cond ((= n i) t)
	((not (primep i)) nil)
	(t (circular-primep-inner n (rotate i)))))

(defun circular-primep (n)
  (circular-primep-inner n (rotate n)))


(defun collect-circular-primes (min max)
  (loop for i = min then (+ 2 i)
     until (> i max)
     when (and (primep i) (circular-primep i))
     collect i))

(print (collect-circular-primes 1 999999))